package view.swing.help;

import java.awt.Component;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import model.Letter;
import model.iview.ITile;
import util.Resources;
import view.swing.CenterTableCellRenderer;

@SuppressWarnings("serial")
public class DistributionWindow extends JFrame {
    private static DistributionWindow lastInstance;
    
    public DistributionWindow(Component parent, Map<ITile, Integer> contenu) {
        super(Resources.getString("Help.Distribution"));
        if (lastInstance != null) {
            lastInstance.dispose();
        }
        lastInstance = this;
        this.buildUI(contenu);
        this.setMinimumSize(new Dimension(250, 400));
        this.setResizable(false);
        this.setLocationRelativeTo(parent);
        
    }

    private void buildUI(Map<ITile, Integer> contenu) {
        this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
        JLabel titre = new JLabel(Resources.getString("Help.Distribution"));
        titre.setFont(titre.getFont().deriveFont(18f));
        titre.setAlignmentX(CENTER_ALIGNMENT);
        titre.setAlignmentY(CENTER_ALIGNMENT);
        this.add(titre);
        
        this.add(Box.createVerticalGlue());
        Object[][] tblContent = new Object[contenu.size()][3];
        List<ITile> lettresTriees = new ArrayList<ITile>(contenu.keySet());
        Collections.sort(lettresTriees, new Comparator<ITile>() {

            @Override
            public int compare(ITile tile0, ITile tile1) {
                return tile0.getLetter().compareTo(tile1.getLetter());
            }
            
        });
        for (int i = 0; i < tblContent.length; i++) {
            ITile tuile = lettresTriees.get(i);
            if (tuile.getLetter() == Letter.BLANK) {
                tblContent[i][0] = Resources.getString("Bag.Joker");
            } else {
                tblContent[i][0] = tuile.getLetter().toString();
            }
            tblContent[i][1] = tuile.getScore();
            tblContent[i][2] = contenu.get(tuile);
        }
        
        JTable table = new JTable(tblContent, new Object[] { Resources.getString("Bag.Letter"), Resources.getString("Bag.LetterScore"), Resources.getString("Bag.Quantity") });
        table.setDragEnabled(false);
        table.setEnabled(false);
        table.getTableHeader().setReorderingAllowed(false);
        table.setDefaultRenderer(Object.class, new CenterTableCellRenderer());
        table.getTableHeader().setDefaultRenderer(new CenterTableCellRenderer());
        table.getTableHeader().setResizingAllowed(false);
        
        JScrollPane jsp = new JScrollPane(table);
        this.add(jsp);
        
    }
}
